package com.nageoffer.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nageoffer.shortlink.admin.common.biz.user.UserContext;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.common.convention.result.Result;
import com.nageoffer.shortlink.admin.dao.entity.GroupDO;
import com.nageoffer.shortlink.admin.dao.mapper.GroupMapper;
import com.nageoffer.shortlink.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.nageoffer.shortlink.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.nageoffer.shortlink.admin.dto.resp.ShortLinkGroupRespDTO;
import com.nageoffer.shortlink.admin.remote.ShortLinkRemoteService;
import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.nageoffer.shortlink.admin.service.GroupService;
import com.nageoffer.shortlink.admin.toolkit.RandomGenerator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.nageoffer.shortlink.admin.common.constant.RedisCacheConstant.LOCK_GROUP_CREATE_KEY;

/**
 * 短链接分组接口实现层
 * 公众号：马丁玩编程，回复：加群，添加马哥微信（备注：link）获取项目资料
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

	private final RedissonClient redissonClient;

	@Value("${short-link.group.max-num}")
	private Integer groupMaxNum;

	/**
	 * 后续重构为 SpringCloud Feign 调用
	 */
	ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
	};

	@Override
	public void saveGroup(String groupName) {
		saveGroup(UserContext.getUsername(), groupName);
	}

	@Override
	public void saveGroup(String username, String groupName) {
		RLock lock = redissonClient.getLock(String.format(LOCK_GROUP_CREATE_KEY, username));
		lock.lock();
		try {
			LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
					.eq(GroupDO::getUsername, username)
					.eq(GroupDO::getDelFlag, 0);
			List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
			if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() >= groupMaxNum) {
				throw new ClientException(String.format("已超出最大分组数：%d", groupMaxNum));
			}
			String gid;
			do {
				gid = RandomGenerator.generateRandom();
			} while (!hasGid(username, gid));
			GroupDO groupDO = GroupDO.builder()
					.gid(gid)
					.sortOrder(0)
					.username(username)
					.name(groupName)
					.build();
			baseMapper.insert(groupDO);
		} finally {
			lock.unlock();
		}
	}

	@Override
	public List<ShortLinkGroupRespDTO> listGroup() {
		LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
				.eq(GroupDO::getDelFlag, 0)
				.eq(GroupDO::getUsername, UserContext.getUsername())
				.orderByDesc(GroupDO::getSortOrder)
				.orderByDesc(GroupDO::getUpdateTime);
		List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
		List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);


		Result<List<ShortLinkGroupCountQueryRespDTO>> result =
				shortLinkRemoteService.listGroupShortLinkCount(
						groupDOList.stream()
								.map(GroupDO::getGid)
								.toList()
				);

		shortLinkGroupRespDTOList.forEach(each -> {
			result.getData().stream()
					.filter(item -> Objects.equals(item.getGid(), each.getGid()))
					.findFirst()
					.ifPresent(item -> each.setShortLinkCount(item.getShortLinkCount()));
			each.setShortLinkCount(Optional.ofNullable(each.getShortLinkCount()).orElse(0));
		});


		return shortLinkGroupRespDTOList;
	}

	@Override
	public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
		LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
				.eq(GroupDO::getUsername, UserContext.getUsername())
				.eq(GroupDO::getGid, requestParam.getGid())
				.eq(GroupDO::getDelFlag, 0);
		GroupDO groupDO = new GroupDO();
		groupDO.setName(requestParam.getName());
		baseMapper.update(groupDO, updateWrapper);
	}

	@Override
	public void deleteGroup(String gid) {
		LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
				.eq(GroupDO::getUsername, UserContext.getUsername())
				.eq(GroupDO::getGid, gid)
				.eq(GroupDO::getDelFlag, 0);
		GroupDO groupDO = new GroupDO();
		groupDO.setDelFlag(1);
		baseMapper.update(groupDO, updateWrapper);
	}

	@Override
	public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
		requestParam.forEach(each -> {
			GroupDO groupDO = GroupDO.builder()
					.sortOrder(each.getSortOrder())
					.build();
			LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
					.eq(GroupDO::getUsername, UserContext.getUsername())
					.eq(GroupDO::getGid, each.getGid())
					.eq(GroupDO::getDelFlag, 0);
			baseMapper.update(groupDO, updateWrapper);
		});
	}

	private boolean hasGid(String username, String gid) {
		LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
				.eq(GroupDO::getGid, gid)
				.eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()));
		GroupDO hasGroupFlag = baseMapper.selectOne(queryWrapper);
		return hasGroupFlag == null;
	}
}
